package com.ck.serviceImpl;

import java.util.Date;
import java.util.Map;

import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import com.ck.dao.BanjiDAO;
import com.ck.dao.StudentDAO;
import com.ck.domain.Banji;
import com.ck.domain.Student;
import com.ck.service.StudentService;

public class StudentServiceImpl implements StudentService {
	
	private StudentDAO studentDAO;
	private BanjiDAO banjiDAO;

	public void setStudentDAO(StudentDAO studentDAO) {
		this.studentDAO = studentDAO;
	}

	public void setBanjiDAO(BanjiDAO banjiDAO) {
		this.banjiDAO = banjiDAO;
	}

	public Student gainStudent(String username) {
		return studentDAO.getStudentByUsername(username);
	}

	public Student gainStudent(Integer id) {
		return studentDAO.getStudentById(id);
	}

	public Banji gainBanji(Integer id) {
		return banjiDAO.getBanjiById(id);
	}

	public boolean editStudentOwnInfo(Student student) {
		student.setCst_modify(new Date());
		studentDAO.updateStudentOwnInfo(student);
		return true;
	}

	public boolean validatePassword(Student student, String confirmPassword,
			Map model) {
		if(confirmPassword.equals(student.getPassword())){
			return true;
		} else {
            model.put("error_confirmPassword", "两次密码输入不一致！");
            return false;
        }
	}

	private Student md5(Student student) {
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        student.setPassword(md5.encodePassword(student.getPassword(), new String(
                "canyouguessme")));
        return student;
    }

    private String md5(String password) {
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        password = md5.encodePassword(password, new String("canyouguessme"));
        return password;
    }
    
	public boolean editStudentOwnPassword(String oldPassword, Student student,
			Map model) {
		Student dbStudent = studentDAO.getStudentById(student.getId());

		if(dbStudent.getPassword().equals(md5(oldPassword))){
			md5(student);
			student.setCst_modify(new Date());
			studentDAO.updateStudentOwnPassword(student);
			return true;
		}else{
			model.put("error_oldPassword", "原密码不正确！");
            return false;
		}
	}

}
